let app = getApp();
import { CategoryModel } from '../../models/CategoryModel.js'
let category = new CategoryModel()
const UTIL = require('../../utils/util');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    scrollTop: 0, //默认距离顶部为0
    collegeCur: -1,//顶部高亮
    leftclass: -1,//左侧高亮
    leftList:[], //左侧栏目列表
    rightTopList: [], //顶部栏目
    products:[], //右侧产品
    curNav: '', //默认左侧第一个栏目id
    rightNav:'', //默认顶部栏目id
    showList: false, //小面板
    page: 0, //页数
    size: 10, //条数
    nodata: false,//没有更多数据了
    aWeek:[],//未来七天时间
    searchName: "搜索商品",
    showSkeleton: true   //骨架屏显示隐藏
  },
  totalPages: 0, // 总页数

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (event) {
    let that = this;
    let res = app.globalData
    that.rightTop()
    that.data_time()
    that.loadArticles(res.options);
    if(res.index !==null){
      that.setData({
        collegeCur:res.index - 1,
        scrollLeft: (res.index - 2) * 176,
        leftclass:-1,
        rightNav:res.options.rightNav
      })
    }else{
      that.setData({
        rightNav:res.options.rightNav
      })
    }

    setTimeout(() => {     //3S后隐藏骨架屏
			that.setData({
				showSkeleton: false
			})
		}, 1000)
  },
  // 顶部栏目
  rightTop:function(){
    category.getCateGory(res=>{
      console.log(res)
      let rightTop = res.result.data.data
      console.log(rightTop[0].id)
      this.setData({
        rightTopList:rightTop
      })
    })
  },
  // 顶部栏目点击事件
  onRightTab:function(e){
    // 改变的地方
    let that = this
    let res = e.currentTarget.dataset
    //当前不能重复点击
    if(that.data.collegeCur+1 == res.index){return;}
    if(that.data.showList){
      that.setData({
        showList:false
      })
    }
    //发送云函数参数
    let rightNav = res.id;
    let curNav = res.idx
    let options = {rightNav:rightNav,curNav:curNav,page:0}
    console.log(options)
    that.loadArticles(options);
    that.setData({
      page:0,
      number:0,
      isAllLoaded:false,
      rightNav: rightNav,
      leftclass:-1,
      collegeCur: res.index - 1,
      scrollLeft: (res.index - 2) * 176,
    })
  },
  //左侧栏目点击事件 
  onLeftTab: function (e) {
    console.log(e);
    let res = e.currentTarget.dataset;
    let rightNav = this.data.rightNav;
    let curNav = e.target.dataset.id;
    //当前不能重复点击
    if(this.data.leftclass+1 == res.index){
      return;
    }
    console.log(rightNav)
    console.log(curNav)
    let options = {rightNav:rightNav,curNav:curNav,page:0}
    this.loadArticles(options);
    this.setData({
      page:0,
      number:0,
      isAllLoaded:false,
      curNav: curNav,
      leftclass: res.index - 1,
      leftTop: (res.index - 3) * 102,
    })
  },  
  //右侧分类显示商品 
  loadArticles:function(type){
    if(this.data.page <=0){ this.selectComponent("#loading").show();}
    category.getCateGoryProduct(type, data => {
      if(this.data.page <=0){ this.selectComponent("#loading").hide();}
      console.log(data)
      // 获取 总条数
      const product = data.result.data.list[0]
      const total = product.totalStaff;
      // 计算总页数
      this.totalPages = Math.ceil(total / this.data.size) - 1;
      // 显示购物车数量
      this.scanCarts(product.data)
      if (this.data.page == 0) {
        this.setData({
          products:product.data
        })
      }else{　　　　　　　　　　　
        this.setData({
          products:[...this.data.products, ...product.data],
          loading:  false,
          isAllLoaded: false
        })
      }
    })
  },
  //加载更多
  scrollLower:function(){
    let that = this;
    let rightNav = that.data.rightNav
    let curNav = that.data.rightNav
    if(that.data.loading || that.data.isAllLoaded) return;
    that.setData({
      loading: true,
    })
    setTimeout(() => {
      if (that.data.page >= that.totalPages) {
          wx.showToast({
            title: "我是有底线的",
            icon: "none",
          });
          that.setData({
            loading: false,
            isAllLoaded: true
          })
      } else {
          let page = that.data.page
          page = page + 1
          let options = {rightNav,curNav,page}
          that.data.page = page
          console.log(page)
          that.loadArticles(options);
      }
    }, 1000)

  },
   
  onShow: function(options){
    let that = this;
    that.scanCarts(that.data.products)
  },
  onReady: function() {
    // 页面首次渲染完毕时执行
  },
  onHide:function(options){
   
  },

  //展示列表小面板
  showlist() {
    let that = this;
    that.setData({
      showList: !that.data.showList,
    })
  },
  //扫描购物车统计购物车的数量
  scanCarts:function(products){
    let that = this;   
    let carts = wx.getStorageSync('carts') || [] //获取缓存中carts信息
console.log(carts)
    for(var i = 0;i<products.length-1;i++){
      products[i].num = 0
      for(var j = 0;j<carts.length;j++){
        if(products[i]._id == carts[j]._id){
          products[i].num = carts[j].num
        }
      }
    }
    that.setData({
      products:this.data.products
     })
  },

  //添加购物车
  addShopCar(e) {
    console.log(e)
    let that = this
    let products = this.data.products
    const curGood = products.find(ele => {
      return ele._id == e.currentTarget.dataset.id
    })
    console.log(curGood)
    let arr = that.data.aWeek[4]
    curGood.day = arr.day

    curGood.num += 1;
    console.log(curGood)
    //缓存购物车数据
    let carts = wx.getStorageSync('carts') || []
    if(carts.length == 0){
      carts.push(curGood);
    }else{
      let hasInfo = this._checkProduct(curGood._id, carts)
      if(hasInfo.index == -1){
        carts.push(curGood);
      }else if(hasInfo.index != -1){
        carts[hasInfo.index].num = curGood.num
      }
    }
    wx.setStorageSync('carts',carts)

    that.setData({
      products: products
    })
    console.log(curGood)
    if (!curGood) {
      return
    }
    //库存
    if (curGood.stock <= 0) {
      wx.showToast({
        title: '已售罄~',
        icon: 'none'
      })
      return
    }

    category.addCart(curGood, data => {
      console.log(data)
      if(data.errMsg == "cloud.callFunction:ok"){
          wx.showToast({
            title: '已添加',
            icon: 'success'
          })
      }
    })
  },
  /*购物车中是否已经存在该商品*/
  _checkProduct(id, arr) {
    let item, result = { index: -1 };
    for (let i = 0; i < arr.length; i++) {
        item = arr[i];
        if (item._id == id) {
            result = {
                index: i,
                data: item
            }
            break;
        }
    }
    return result;
  },
  // 获取未来七天的函数
  data_time:function(){
    var arr = []
    for (let i = 0; i < 5; i++) {
      arr.push(UTIL.dealTime(i))
    }
    console.log(arr)
    arr[0].day = '今天'
    this.setData({
      aWeek: arr
    })
  },
    // 详情页
    onDetails:function(e){
      wx.navigateTo({
        url: "../commodity-details/commodity-details?id=" + e.currentTarget.dataset.id
      })
    },
  // 获取滚动条当前位置
  // onPageScroll: function (e) {
  //   console.log(e)
  //   this.setData({
  //     scrollTop: e.scrollTop,
  // });
  // }

})